import time

from common.logger.log import log_
from autoTask.tools import Slider, Picture
from autoTask.Base import Login_new
from request.remote import code as remote_code
from request.smtp import Action as smtp_Action


class PinDuoDuo(Login_new):
    def __init__(self, account: str, password: str, **kwargs):
        super().__init__(account, password, **kwargs)

    def action(self):
        self.login()
        if self.login_state:
            log_.info('登录成功')
        else:
            raise Exception('登录失败')

    def login_step(self):
        log_.info('执行登录操作')
        page, hand = self.page, self.hand
        page.get('https://mms.pinduoduo.com/login/')
        if 'mms.pinduoduo.com/login' not in page.url:
            raise Exception('不在登录页面')
        hand.click('tx:账号登录')
        hand.fill(self.account, 'x://input[@id="usernameId"]')
        hand.fill(self.password, 'x://input[@id="passwordId"]')
        # 监听数据包
        self.listen_to(
            'https://mms.pinduoduo.com/janus/api/auth',
            next_step={'func': hand.click, 'args': {'ele': 'x://div[@class="info-content"]/button'}},
            to_dest=self.auth_check
        )

    def logout_step(self):
        log_.info('执行退出操作')
        page = self.page
        page.get('https://mms.pinduoduo.com/janus/api/logout')
        self.login_step()

    def login(self):
        page = self.page
        url = 'https://mms.pinduoduo.com/home'
        page.get(url)
        if page.url == url:
            log_.info('已登录, 检测账号是否相同')
            self.account_same()
        else:
            log_.info('未登录')
            self.login_step()

    def account_same(self):
        page = self.page
        name = page.ele('x://div[@class="user-name-id"]/span')
        if not name:
            raise Exception('不可预知错误')
        if name.text == self.account:
            log_.info('账号相同')
            self.login_state = True
        else:
            log_.debug('账号不相同')
            self.logout_step()

    def auth_check(self, response):
        log_.debug(response or 'auth_check Response is None')
        if not response:
            self.account_same()
            return
        if response.get('success') in [True, 'True', 'true']:
            self.login_state = True
            return
        errCode = response.get('errorCode')
        errMsg = response.get('errorMsg')
        if errCode == 402:
            raise Exception('账号密码错误')
        elif errMsg == '需要手机验证' or errCode == 2000020:
            phone = response['result']
            self.phone_code(phone)
        elif errMsg == '验证码错误或已失效' or errCode == 4000003:
            raise Exception('验证码错误或已失效, 任务中断')
        else:
            raise Exception(errMsg)

    def phone_code(self, phone):
        if not self.email:
            raise Exception('登录需要验证码, 预留邮箱为空->任务结束')
        page, hand = self.page, self.hand
        hand.click('tx:获取验证码')
        self.tid = remote_code.add(phone)
        smtp_Action(self.email).phone_code(self.tid)
        self.phone_code_step()

    def phone_code_step(self, count=0):
        # 八分钟左右
        max_count = 50
        if count >= max_count:
            raise Exception('等待时间过长, 验证码失效, 任务关闭')
        if self.tid is None:
            raise Exception('tid 为空')
        tid = self.tid
        time.sleep(10)
        log_.debug(f'{tid}, Cur: {count+1}, Max: {max_count}')
        page, hand = self.page, self.hand
        code = remote_code.get(tid)
        if code:
            hand.fill(code, 'x://div[@class="vertify-code"]//input')
            self.listen_to(
                'https://mms.pinduoduo.com/janus/api/auth',
                next_step={'func': hand.click, 'args': {'ele': 'x://section[@class="verify-phone-container"]/button'}},
                to_dest=self.auth_check
            )
            return
        self.phone_code_step(count+1)

    # def user_verify(self, response):
    #     log_.debug(f'第{self.slider_tries}次滑块验证尝试, 验证 {response["result"]}')
    #
    # def slider(self):
    #     page, hand = self.page, self.hand
    #     save = Picture.Save()
    #     bg_img_path = save.bytesTo('bg.png', page.ele('x://img[@class="slider-img-bg"]').get_src())
    #     slice_img_path = save.bytesTo('slice.png', page.ele('x://img[@class="slider-item"]').get_src())
    #     distance = Slider.Contrast(bg_img_path, slice_img_path).distance(show=False)
    #     btn = page.ele('x://div[@class="slide-button-wrapper"]')
    #     hand.drag_x(btn, distance - 28)


if __name__ == '__main__':
    # PinDuoDuo('德国赫巴兹客服经理', '12345678zZ', email='2804645403@qq.com').action()
    PinDuoDuo('赫巴兹官旗强', 'Hbz123456').action()
    # PinDuoDuo('赫巴兹锅具官旗强', 'HHz123456', email='2054401068@qq.com').action()

    # PinDuoDuo('12312zzz1', '123456').action()
